<?php

namespace Frieza\Modules\Topic\Controllers;

use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\NewTag\Tag;
use Doraemon\model\Topic\TopicActivity as mTopicActivity;
use Doraemon\service\Tag\TagList;
use Doraemon\service\Topic\TopicHot as sTopicHot;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\Topic\RankList;

class TopicHotController extends Controller
{
    public function index(Content $content, Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $order = ['sort' => 'ASC', 'id' => 'DESC'];

        $hot = sTopicHot::getListByWhere([], $limit, $order);
        $gridModel = new pGridDataModel($hot['list'], $hot['total'], [
            'perPage' => $pageSize,
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();

            $grid->column('id', 'ID')->sort('sort');
            $grid->column('title', '榜单');
            $grid->column('start_time', '展示开始时间')->display(function ($counter) {
                return empty($this->show_type) ? date('Y-m-d H:i:s', $this->addtime) : date('Y-m-d H:i:s', $counter);
            });
            $grid->column('end_time', '展示结束时间')->display(function ($counter) {
                return empty($this->show_type) ? '永久生效' : date('Y-m-d H:i:s', $counter);
            });
            $url = Hhzurl::getDomain();

            Admin::script($this->setScript($url));
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
                // 去掉查看
                $actions->disableView();

                $actions->prepend('<a class="setTop label  label-info"  style="margin: 4px" data-id="" href="/admin/topic/hot/'.$actions->row->id.'/info">查看榜单</a>');
                $actions->prepend('<a class="setView label  label-info" style="margin: 4px"  href="/admin/topic/hot/edit/' . $actions->row->id . '">编辑</a>');
                $actions->prepend('<a class="setViews label  label-info"  data-id="' . $actions->row->id . '"> 预览 </a>');
            });
        });
        return $content
            ->header('话题榜单管理')
            ->breadcrumb(['text' => '话题榜单管理', 'url' => '/admin/topic/hot/index'])
            ->body($listGrid);
    }

    public function create(Content $content, $id = 0)
    {
        $info = [];
        if ($id) {
            $info = sTopicHot::getInfo($id);
            $info['tag'] = json_decode($info['tag'], true);
            $info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
            $info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);
        }
        $form = new Form($info);

        $form->hidden('id', '热榜ID');
        $form->text('title', '榜单主题')->required();
//        $form->number('hot_num', '上榜话题数量')->required();
        $form->textarea('topic_id', '话题ID')->required()->help('多个话题ID,隔开，话题ID不低于3个');
        $form->radio('show_type', '榜单展示时间')->required()->options([1 => '指定时间段', 0 => '永久生效']);
        $form->datetime('start_time', '开始时间')->default(date('Y-m-d'));
        $form->datetime('end_time', '结束时间')->default(date('Y-m-d',strtotime('+1 day')));
        $form->imgUpload('background_img', '榜单背景图', false);
        $form->imgUpload('share_img', '榜单分享图', false);
        $form->action('/admin/topic/hot/save');
        return $content
            ->header('创建话题榜单')
            ->breadcrumb(['text' => '话题管理管理', 'url' => '/topic/new'], ['text' => '话题榜单编辑'])
            ->row($form->render());
    }
    public function setScript($url)
    {
        return <<<SCRIPT
        $('.setViews').unbind('click').click(function() {
            var id = $(this).attr('data-id');
            var url = '{$url}/community/topic-rank?id='+id
            console.log(url);
            layer.open({
                type: 2,
                title: '搜索结果',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['400px', '700px'],
                content: url,
            });
		});
SCRIPT;
    }

    public function save(Request $request)
    {
        $param = $request->all();
        $id = $param['id'];
        unset($param['id'], $param['_token']);
//        $param['tag'] = array_filter($param['tag']);
//        $param['tag'] = json_encode($param['tag'], JSON_UNESCAPED_UNICODE);

        if (mb_strlen($param['title']) > 20) {
            throw new InputErrorException('最多支持 20 个字符', InputErrorException::DEFAULT_CODE, 'title');
        }
//        if (empty($param['hot_num']) || !ctype_digit($param['hot_num'])) {
//            throw new InputErrorException('上榜话题数量为大于 0 ', InputErrorException::DEFAULT_CODE, 'hot_num');
//        }
        $topicId = array_unique(explode(',', $param['topic_id']));
        if (count($topicId) < 3) {
            throw new InputErrorException('话题ID不能少与3个', InputErrorException::DEFAULT_CODE, 'topic_id');
        }
        if ($param['show_type'] == 1) {
            if (empty($param['start_time'])) {
                throw new InputErrorException('请选择榜单开始时间', InputErrorException::DEFAULT_CODE, 'start_time');
            }
            if (empty($param['end_time'])) {
                throw new InputErrorException('请选择榜单结束时间', InputErrorException::DEFAULT_CODE, 'end_time');
            }
            if ($param['end_time'] <= $param['start_time']) {
                throw new InputErrorException('请选择榜单正确的时间范围', InputErrorException::DEFAULT_CODE, 'start_time');
            }
        }
        if (empty($param['background_img'])) {
            throw new InputErrorException('请选择榜单背景图', InputErrorException::DEFAULT_CODE, 'background_img');
        }
        if (empty($param['share_img'])) {
            throw new InputErrorException('请选择分享图', InputErrorException::DEFAULT_CODE, 'share_img');
        }
        $param['start_time'] = strtotime($param['start_time']);
        $param['end_time'] = strtotime($param['end_time']);
        if ($id) {//修改
            $resultId = sTopicHot::edit($id, $param);
        } else {
            $param['admin_id'] = Admin::user()->id;
            $resultId = sTopicHot::add($param);
        }
        if (empty($resultId)) {
            $message['error'] = new MessageBag(['title' => '操作失败']);
        } else {
            //RankList::setRank($resultId);
            $message['success'] = new MessageBag(['title' => '保存成功']);
        }
        return redirect('/admin/topic/hot/index')->with($message);
    }

    /**
     * 拖动排序
     *
     * @param Request $request
     */
    public function sort(Request $request)
    {
        $params = $request->all();
        $hot = $params['sort'];
        foreach ($hot as $id => $sort) {
            sTopicHot::edit($id, ['sort' => $sort]);
        }
    }
}